package cn.elead.chaos.sso.server.web.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.elead.chaos.core.util.StringUtils;
import cn.elead.chaos.framework.web.global.ApiAssert;
import cn.elead.chaos.framework.web.global.ErrorCodeEnum;
import cn.elead.chaos.sso.server.constants.UserConstants;
import cn.elead.chaos.sso.server.web.system.domain.SysDept;
import cn.elead.chaos.sso.server.web.system.domain.SysRole;
import cn.elead.chaos.sso.server.web.system.domain.SysUser;
import cn.elead.chaos.sso.server.web.system.domain.Ztree;
import cn.elead.chaos.sso.server.web.system.mapper.SysDeptMapper;
import cn.elead.chaos.sso.server.web.system.mapper.SysUserMapper;
import cn.elead.chaos.sso.server.web.system.service.ISysDeptService;
import cn.hutool.core.util.ObjectUtil;

/**
 * 部门管理 服务实现
 * 
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService {
	
	@Autowired
	private SysDeptMapper deptMapper;
	
	@Autowired
	private SysUserMapper userMapper;

	@Autowired
	private RestTemplate restTemplate;

	/**
	 * 查询部门管理数据
	 * 
	 * @param dept 部门信息
	 * @return 部门信息集合
	 */
	@Override
	// @DataScope(deptAlias = "d")
	public List<SysDept> selectDeptList(SysDept dept) {
		return deptMapper.selectDeptList(dept);
	}

	/**
	 * 查询部门管理树
	 * 
	 * @param dept 部门信息
	 * @return 所有部门信息
	 */
	@Override
	// @DataScope(deptAlias = "d")
	public List<Ztree> selectDeptTree(SysDept dept) {
		List<SysDept> deptList = deptMapper.selectDeptList(dept);
		List<Ztree> ztrees = initZtree(deptList);
		return ztrees;
	}

	/**
	 * 根据角色ID查询部门（数据权限）
	 *
	 * @param role 角色对象
	 * @return 部门列表（数据权限）
	 */
	@Override
	public List<Ztree> roleDeptTreeData(SysRole role) {
		Long roleId = role.getRoleId();
		List<Ztree> ztrees = new ArrayList<Ztree>();
		List<SysDept> deptList = selectDeptList(new SysDept());
		if (ObjectUtil.isNotNull(roleId)) {
			List<String> roleDeptList = deptMapper.selectRoleDeptTree(roleId);
			ztrees = initZtree(deptList, roleDeptList);
		} else {
			ztrees = initZtree(deptList);
		}
		return ztrees;
	}

	/**
	 * 对象转部门树
	 *
	 * @param deptList 部门列表
	 * @return 树结构列表
	 */
	public List<Ztree> initZtree(List<SysDept> deptList) {
		return initZtree(deptList, null);
	}

	/**
	 * 对象转部门树
	 *
	 * @param deptList     部门列表
	 * @param roleDeptList 角色已存在菜单列表
	 * @return 树结构列表
	 */
	public List<Ztree> initZtree(List<SysDept> deptList, List<String> roleDeptList) {

		List<Ztree> ztrees = new ArrayList<Ztree>();
		boolean isCheck = ObjectUtil.isNotNull(roleDeptList);
		for (SysDept dept : deptList) {
			if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
				Ztree ztree = new Ztree();
				ztree.setId(dept.getDeptId());
				ztree.setpId(dept.getParentId());
				ztree.setName(dept.getDeptName());
				ztree.setTitle(dept.getDeptName());
				if (isCheck) {
					ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
				}
				ztrees.add(ztree);
			}
		}
		return ztrees;
	}

	/**
	 * 查询部门人数
	 * 
	 * @param parentId 部门ID
	 * @return 结果
	 */
	@Override
	public int selectDeptCount(Long parentId) {
		SysDept dept = new SysDept();
		dept.setParentId(parentId);
		return deptMapper.selectDeptCount(dept);
	}

	/**
	 * 查询部门是否存在用户
	 * 
	 * @param deptId 部门ID
	 * @return 结果 true 存在 false 不存在
	 */
	@Override
	public boolean checkDeptExistUser(Long deptId) {
		int result = deptMapper.checkDeptExistUser(deptId);
		return result > 0 ? true : false;
	}

	/**
	 * 删除部门管理信息
	 * 
	 * @param deptId 部门ID
	 * @return 结果
	 */
	@Override
	public int deleteDeptById(Long deptId) {
		return deptMapper.deleteDeptById(deptId);
	}

	/**
	 * 新增保存部门信息
	 * 
	 * @param dept 部门信息
	 * @return 结果
	 */
	@Override
	public int insertDept(SysDept dept) {
		SysDept info = deptMapper.selectDeptById(dept.getParentId());
		// 如果父节点不为"正常"状态,则不允许新增子节点
		if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
			ApiAssert.failure(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("部门停用，不允许新增"));
		}
		dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
		return deptMapper.insertDept(dept);
	}

	/**
	 * 修改保存部门信息
	 * 
	 * @param dept 部门信息
	 * @return 结果
	 */
	@Override
	@Transactional
	public int updateDept(SysDept dept) {
		SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
		SysDept oldDept = selectDeptById(dept.getDeptId());
		if (ObjectUtil.isNotNull(newParentDept) && ObjectUtil.isNotNull(oldDept)) {
			String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
			String oldAncestors = oldDept.getAncestors();
			dept.setAncestors(newAncestors);
			updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
		}
		int result = deptMapper.updateDept(dept);
		if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
			// 如果该部门是启用状态，则启用该部门的所有上级部门
			updateParentDeptStatus(dept);
		}
		return result;
	}

	/**
	 * 修改该部门的父级部门状态
	 * 
	 * @param dept 当前部门
	 */
	private void updateParentDeptStatus(SysDept dept) {
		String updateBy = dept.getUpdateBy();
		dept = deptMapper.selectDeptById(dept.getDeptId());
		dept.setUpdateBy(updateBy);
		deptMapper.updateDeptStatus(dept);
	}

	/**
	 * 修改子元素关系
	 * 
	 * @param deptId       被修改的部门ID
	 * @param newAncestors 新的父ID集合
	 * @param oldAncestors 旧的父ID集合
	 */
	public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
		List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
		for (SysDept child : children) {
			child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
		}
		if (children.size() > 0) {
			deptMapper.updateDeptChildren(children);
		}
	}

	/**
	 * 根据部门ID查询信息
	 * 
	 * @param deptId 部门ID
	 * @return 部门信息
	 */
	@Override
	public SysDept selectDeptById(Long deptId) {
		return deptMapper.selectDeptById(deptId);
	}

	/**
	 * 校验部门名称是否唯一
	 * 
	 * @param dept 部门信息
	 * @return 结果
	 */
	@Override
	public int checkDeptNameUnique(SysDept dept) {
		Long deptId = ObjectUtil.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
		SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
		if (ObjectUtil.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
			return UserConstants.DEPT_NAME_NOT_UNIQUE;
		}
		return UserConstants.DEPT_NAME_UNIQUE;
	}

	/**
	 * 同步部门
	 */
	@Override
	@Transactional
	public void init() {

		Map<Long, SysDept> deptMap = new HashMap<>();
		
		Map<String, SysDept> deptNameMap = new HashMap<>();
		
		Map<String, Long> userMap = new HashMap<>();


		HttpHeaders headers = new HttpHeaders();// header参数
		headers.add("username", "sso");
		headers.add("password", "sso");
		headers.setContentType(MediaType.APPLICATION_JSON);

		HttpEntity<Void> request = new HttpEntity<>(headers); // 组装

		String url = "http://oa.e-lead.cn:8090/timesheet/outer/usersSSO";

		ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, request, JSONObject.class);

		if (response.getStatusCode() == HttpStatus.OK) {

			JSONObject body = response.getBody();

			JSONArray datas = body.getJSONArray("data");

			Iterator<Object> iterator = datas.iterator();

			while (iterator.hasNext()) {
				JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(iterator.next()));
				String userId = data.getString("work_no");
				if (StringUtils.isBlank(userId)) {
					System.err.println(data);
					continue;
				}
				
				long maxId = deptMapper.selectDeptByMaxId();
				
				long parentId = 0;
				String department = data.getString("department");
				List<String> departments = Arrays.asList(department.split("-->"));
				for (String deptName : departments) {
					//当前部门是否存在
					SysDept sysDept = deptNameMap.get(deptName);
					if(ObjectUtil.isEmpty(sysDept)) {
						//sysDept = deptMapper.checkDeptNameUnique(deptName, null);
					}
					if(ObjectUtil.isEmpty(sysDept)) {
						sysDept = new SysDept();
						sysDept.setDeptName(deptName);
						sysDept.setParentId(parentId);
						
						long id = ++maxId;
						// 父对象
						SysDept psysDept = deptMap.get(parentId);
						if(ObjectUtil.isEmpty(psysDept)) {
							// 第一条数据
							sysDept.setAncestors(id+"");
						}else {
							sysDept.setAncestors(psysDept.getAncestors()+","+id);
						}
						sysDept.setDeptId(id);
						deptMap.put(id, sysDept);
						deptNameMap.put(deptName, sysDept);
						parentId = id;
						deptMapper.insertDept(sysDept);
					}else {
						parentId = sysDept.getDeptId();
						//ancestors = sysDept.getAncestors();
						deptMap.put(sysDept.getDeptId(), sysDept);
						if(!deptNameMap.containsKey(deptName)) {
							deptNameMap.put(deptName, sysDept);
						}
					}
				}
				userMap.put(userId, parentId);
			}
			
		}
		
		userMap.entrySet().stream().forEach(action->{
			String userId = action.getKey();
			Long deptId = action.getValue();
			
			SysUser sysUser = new SysUser();
			sysUser.setDeptId(deptId);
			sysUser.setUserId(userId);
			userMapper.updateUser(sysUser);
		});
		
	}
}
